package cn.javaSong.service.impl;

import cn.javaSong.common.ResponseHelper;
import cn.javaSong.common.ResponseModel;
import cn.javaSong.entity.Song;
import cn.javaSong.mapper.SongMapper;
import cn.javaSong.service.ISongService;
import cn.javaSong.utils.StringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2024-10-26
 */
@Service
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements ISongService {

    @Value("${songFile}")
    private String songFile;

    @Value("${server.port}")
    private String imgUrl;

    @Resource
    private SongMapper songMapper;

    @Override
    public ResponseModel addSong(MultipartFile request) {
        Song song = new Song();
        if (request.isEmpty() || !request.getContentType().startsWith("audio/mpeg")) {
            return ResponseHelper.successMessage("请上传一个有效的MP3文件");
        }
        try {
            // 获取文件名
            String fileName = request.getOriginalFilename();
            // 重命名文件名
            String names = StringUtil.getCurrentDateStr() + ".mp3";
            // 创建文件路径
            Path filePath = Paths.get(songFile + names);
            // 确保目录存在
            File uploadDir = filePath.getParent().toFile();
            song.setUpdateTime(new Date());
            song.setSname(fileName);
            song.setNames(names);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            this.save(song);
            // 保存文件
            Files.write(filePath, request.getBytes());
            return ResponseHelper.successMessage("文件上传成功: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseHelper.successMessage("文件上传失败");
        }
    }

    @Override
    public ResponseModel addSongs(List<MultipartFile> request) {
        List<String> songName = new ArrayList<>();
        for (MultipartFile res : request) {
            Song song = new Song();
            if (res.isEmpty() || !res.getContentType().startsWith("audio/mpeg")) {
                return ResponseHelper.successMessage("请上传一个有效的MP3文件");
            }
            try {
                // 获取文件名
                String fileName = res.getOriginalFilename();
                songName.add(fileName);
                // 重命名文件名
                String names = StringUtil.getCurrentDateStr() + ".mp3";
                // 创建文件路径
                Path filePath = Paths.get(songFile + names);
                // 确保目录存在
                File uploadDir = filePath.getParent().toFile();
                song.setPath(String.valueOf(filePath));
                song.setUpdateTime(new Date());
                song.setSname(fileName);
                song.setNames(names);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                try {
                    song.setAddress("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + imgUrl + "/song/" + names);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                this.save(song);
                // 保存文件
                Files.write(filePath, res.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseHelper.successMessage("文件上传失败");
            }
        }
        return ResponseHelper.successMessage("文件上传成功: " + songName);
    }

    // 导出数据到Excel
    @Override
    public ResponseModel<Void> exportUsersToExcel(HttpServletResponse response) throws IOException {
        List<Song> songs = songMapper.selectSongs();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("歌曲信息表");

        // 创建标题行
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("歌曲信息");

        // 合并标题单元格（假设标题跨越前3列）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));

        // 创建表头行
        Row headerRow = sheet.createRow(1);
        String[] headers = {"歌曲名称", "转义后名称", "地址","访问地址","创建时间"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 标题及字段居中设置
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleCell.setCellStyle(titleStyle);

        // 填充数据行
        int rowNum = 2;
        for (Song song : songs) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(song.getSname());
            row.createCell(1).setCellValue(song.getNames());
            row.createCell(2).setCellValue(song.getPath());
            row.createCell(3).setCellValue(song.getAddress());
            row.createCell(4).setCellValue(song.getUpdateTime());
        }

        // 设置列宽
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(2);
        sheet.autoSizeColumn(3);
        sheet.autoSizeColumn(4);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=Songs.xlsx");

        workbook.write(response.getOutputStream());
        workbook.close();
        // 返回响应实体，状态码为200（OK），但无实际内容体（因为内容已经写入响应输出流）
        return ResponseHelper.successMessage("导出成功");
    }

    // 从Excel导入数据
    @Transactional
    @Override
    public void importUsersFromExcel(MultipartFile file) throws IOException {
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过标题行
            if (row.getRowNum() == 1) continue; // 跳过表头行
            Song song = new Song();
            song.setSname(row.getCell(0).getStringCellValue());
            song.setNames(row.getCell(1).getStringCellValue());
            song.setPath(row.getCell(2).getStringCellValue());
            song.setAddress(row.getCell(3).getStringCellValue());
            song.setUpdateTime(row.getCell(4).getDateCellValue());
            this.save(song);
        }
        workbook.close();
    }
}
